package cn.xo68.boot.job;

import cn.xo68.boot.job.common.QuartzContants;
import cn.xo68.boot.job.entity.JobLog;
import cn.xo68.boot.job.entity.QuartzJob;
import cn.xo68.boot.job.jdbcstore.LogStoreService;
import cn.xo68.core.util.JsonUtil;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.io.Serializable;
import java.util.Date;
import java.util.Map;

/**
 * 调度任务执行者， quartz的job
 * @author wuxie
 * @date 2018-6-22
 */
@DisallowConcurrentExecution
public class JobExecutor  implements Job,Serializable {

    private final static Logger logger = LoggerFactory.getLogger(JobExecutor.class);

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private JsonUtil jsonUtil;

    @Autowired
    private LogStoreService logStoreService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        JobLog jobLog=new JobLog();

        jobLog.setBeginTime(new Date());

        String jobJson = context.getMergedJobDataMap().getString(QuartzContants.DATAMAP_JOB_ENTITY);
        //logger.debug("job start");
        //logger.debug("job:{}", jobJson);
        QuartzJob quartzJob=jsonUtil.parse(jobJson, QuartzJob.class);
        Scheduler scheduler = context.getScheduler();
        String schedulerName="";
        String schedulerInstanceId="";
        try {
            schedulerName = scheduler.getSchedulerName();
            schedulerInstanceId=scheduler.getSchedulerInstanceId();
        } catch (SchedulerException e) {
            logger.error("读取调度器名称异常", e);
        }
        jobLog.setJobId(quartzJob.getJobId());
        jobLog.setScheduleName(schedulerName);
        jobLog.setScheduleInstance(schedulerInstanceId);
        jobLog.setJobName(quartzJob.getJobName());
        jobLog.setJobGroup(quartzJob.getJobGroup());


        JobProvider jobProvider=getJobProvider(quartzJob.getJobProviderBeanName());
        if(jobProvider!=null){
            Boolean result=true;
            try{
                jobProvider.execute(context, quartzJob);

                jobLog.setJobResult("y");
            }catch (Exception e){
                logger.error("执行调度任务异常",e);
                result=false;
                jobLog.setJobResult("f");
            }

        }else {
            logger.error("调度提供者不在在，beanName:{}", quartzJob.getJobProviderBeanName());
        }
        //logger.debug("job end");
        try {
            jobLog.setEndTime(new Date());
            logStoreService.add(jobLog);
        }catch (Exception e){
            logger.error("记录任务调度日志异常", e);
        }

    }

    protected JobProvider getJobProvider(String jobProviderBeanName){
        Map<String, JobProvider> jobProviderMap = applicationContext.getBeansOfType(JobProvider.class);
        return jobProviderMap.get(jobProviderBeanName);
    }
}
